//
//  YFPlayVideoController.m
//  Victor
//
//  Created by Coollang on 2017/8/18.
//  Copyright © 2017年 coollang. All rights reserved.
//

#import "YFPlayVideoController.h"
#import "UIDevice+XJDevice.h"
#import "HighlightPropertyView.h"
#import "Masonry.h"
#import <AVFoundation/AVFoundation.h>
#import "TrackVideo.h"

#define kLeftViewPortraitWidth 80.0f
#define kLeftViewLandscapeRightWidth 120.f
#define kVideoAspectScale (720.0/1280.0)
#define kTimeerInterval  0.5

#define kStatus @"status"

@interface YFPlayVideoController ()
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playViewHeightCon;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftSuperWidthCon;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topToolViewHeightCon;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftPreViewConstraint;
/** 当前方向 */
@property (nonatomic, assign) UIInterfaceOrientation currentOrientation;

@property (weak, nonatomic) IBOutlet UIView *leftSuperview;

@property (nonatomic, strong) HighlightPropertyView *leftAnimationView;
@property (weak, nonatomic) IBOutlet UIView *playview;

@property (weak, nonatomic) IBOutlet UIButton *plaYbutton;
@property (weak, nonatomic) IBOutlet UILabel *videoName;
@property (weak, nonatomic) IBOutlet VideoSliderView *videoSlider;

@property (weak, nonatomic) IBOutlet UIButton *previousButton;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;

@property (weak, nonatomic) IBOutlet UILabel *currnetTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *previewImageView;
@property (weak, nonatomic) IBOutlet UIView *bottomToolView;
@property (weak, nonatomic) IBOutlet UIView *topToolView;
@property (weak, nonatomic) IBOutlet UIView *maskView;

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) AVPlayerItem *playerItem;

//是否正在播放
@property (nonatomic, assign) BOOL isPlayvideo;
@property (nonatomic, strong) TrackVideo *currentVideo;
@property (nonatomic, strong) NSTimer *timer;


@property (nonatomic, assign)NSInteger tapActionAfterDur;

@end

@implementation YFPlayVideoController  {
    BOOL toolAnimationEnd; // 标记状态操作结束
}

- (void)setTapActionAfterDur:(NSInteger)tapActionAfterDur {
    _tapActionAfterDur = tapActionAfterDur;
    if (tapActionAfterDur * kTimeerInterval >= 2.5) {
        _tapActionAfterDur = 0;
        [self performSelector:@selector(tapGestureAction) withObject:nil afterDelay:0.25];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    toolAnimationEnd = YES;
    [self configuerPlayerView];
    [self configuerSetUpUI];
}


- (void)configuerPlayerView {
    if (_index == 0) {
        _previousButton.enabled = NO;
    }
    if (_index == _videoFiles.count - 1) {
        _nextButton.enabled = NO;
    }
    self.player = [[AVPlayer alloc] init];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = self.playview.bounds;
    [self.playview.layer insertSublayer:self.playerLayer atIndex:0];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureAction)];
    [self.maskView addGestureRecognizer:tapGes];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setPlayerUrl];
}

- (IBAction)sliderValueChange:(UISlider *)sender {
    if (self.player.status == AVPlayerStatusReadyToPlay){
        [self.player pause];
        self.isPlayvideo = NO;
        self.tapActionAfterDur = 0;
        // 计算脱出的当前秒数
        Float64 totalTime = CMTimeGetSeconds(self.playerItem.duration);
        CGFloat dragedSeconds = floorf(totalTime * sender.value);
        // 转换成CMTime
        CMTime dragedCMTime = CMTimeMakeWithSeconds((Float64) dragedSeconds, 1);
        [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
            [self playVideo];
        }];
    }
}

- (void)addObserverAndNotification {
     // 播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEndVideo) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    // 监听视频状态
    [_playerItem addObserver:self
                  forKeyPath:kStatus
                     options:(NSKeyValueObservingOptionNew)
                     context:nil];
}

- (void)playEndVideo {
    [self pasueVideo];
    // 设置预览图
    [self.player seekToTime:CMTimeMake(0, self.playerItem.duration.timescale) completionHandler:^(BOOL finished) {
    }];
}

- (void)enterBackground {
    [self pasueVideo];
}

- (void)tapGestureAction {
    if (self.currentOrientation == UIInterfaceOrientationPortrait) {
        return;
    }
    // 判断底部工具栏是否在显示
    if (self.bottomToolView.hidden == YES){
        [self showOrHiddenToolView:NO];
        self.tapActionAfterDur = 0;
//        [self performSelector:@selector(showOrHiddenToolView:) withObject:@(1) afterDelay:3];
    }else {
        [self showOrHiddenToolView:YES];
    }
}

- (void)showOrHiddenToolView:(BOOL)hidden {
    if (toolAnimationEnd == NO) {
        return;
    }
    if (self.currentOrientation == UIInterfaceOrientationPortrait) {
        hidden = NO;
    }
    toolAnimationEnd = NO;
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.bottomToolView.alpha = !hidden;
        self.topToolView.alpha = !hidden;
    } completion:^(BOOL finished) {
        toolAnimationEnd = YES;
        self.bottomToolView.hidden = hidden;
        self.topToolView.hidden = hidden;
    }];
}

// 播放与暂停
- (void)playVideo {
    [self.player play];
    self.isPlayvideo = YES;
    self.plaYbutton.selected = YES;
    
}

- (void)pasueVideo {
    [self.player pause];
    self.isPlayvideo = NO;
    self.plaYbutton.selected = NO;
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    AVPlayerItem *item = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:kStatus]) {
        // 获取更改后的状态
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
        if (status == AVPlayerStatusReadyToPlay) {
            // 播放
            [self playVideo];
            if (self.timer == nil) {
                [self timer];
            }
        } else if (status == AVPlayerStatusFailed) {
            YFLog(@"播放失败");
        }else {
            YFLog(@"未知错误");
        }
    }else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
//        NSTimeInterval timeInterval = [self availableDurationRanges]; // 缓冲时间
//        CGFloat totalDuration = CMTimeGetSeconds(_playerItem.duration); // 总时间
//        [self setProgress:timeInterval / totalDuration animated:YES]; // 更新缓冲条
    }
}

- (void)setPlayerUrl {
   
    if (self.videoFiles.count > self.index){
        self.currentVideo = self.videoFiles[self.index];
        NSURL *videoUrl = [NSURL fileURLWithPath:self.currentVideo.documentPath];
        [self updatePlayerWithURL:videoUrl];
       
    }
}
- (void)updatePlayerWithURL:(NSURL *)url {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    if (self.playerItem){
        [self.playerItem removeObserver:self forKeyPath:kStatus];
    }
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    CGSize size = self.playerItem.presentationSize;
    [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
    self.currnetTimeLabel.text = @"00:00";
    Float64 totalSecond = CMTimeGetSeconds(self.playerItem.duration);
    NSInteger totalMin = (totalSecond / 60);
    NSInteger totalSec =  (NSInteger)totalSecond % 60;
    self.totalTimeLabel.text = [NSString stringWithFormat:@"%02zd:%02zd",totalMin,totalSec];
    [self addObserverAndNotification];
}

- (void)updateLeftAirView:(VideoTrackItem *)item {
    NSInteger swingSpeed = [YFUserDefaults generalMetricSystemUnit] ? item.speed:round([Common kmhToMph:item.speed]);
    [self.leftAnimationView animateToValues:@[@(swingSpeed),@(item.strength),@(item.swingTime)]];
}

- (void)configuerSetUpUI {
    [self.videoSlider setThumbImage:[UIImage imageNamed:@"滑块"] forState:UIControlStateNormal];
    [self.videoSlider setThumbImage:[UIImage imageNamed:@"滑块"] forState:UIControlStateHighlighted];
    // 进来默认为横屏
    [UIDevice setOrientation:UIInterfaceOrientationLandscapeRight];
    self.currentOrientation = UIInterfaceOrientationLandscapeRight;
    [self changeViewOrientation:CGSizeMake(MAX(kYFScreenWidth, kYFScreenHeight), MIN(kYFScreenWidth, kYFScreenHeight)) aniTime:0.25];
    self.playerLayer.frame = CGRectMake(0, 0, MAX(kYFScreenWidth, kYFScreenHeight),  MIN(kYFScreenWidth, kYFScreenHeight));
    self.bottomToolView.hidden = YES;
    self.topToolView.hidden = YES;
    self.bottomToolView.alpha = 0;
    self.topToolView.alpha = 0;
    
    self.leftAnimationView = [[HighlightPropertyView alloc] initWithFrame:CGRectMake(0, 0, self.leftSuperWidthCon.constant, self.playViewHeightCon.constant)];
    [self.leftSuperview addSubview:self.leftAnimationView];
}

- (IBAction)playButtonClick:(UIButton *)sender {
    self.tapActionAfterDur = 0;
    if (sender.isSelected == NO){
        [self playVideo];
    }else {
        [self pasueVideo];
    }
}

- (IBAction)backButtonClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.playerItem removeObserver:self forKeyPath:kStatus];
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (IBAction)changeScreenOrientation:(id)sender {
    if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeRight){
                [UIDevice setOrientation:UIInterfaceOrientationPortrait];
    }else {
        [UIDevice setOrientation:UIInterfaceOrientationLandscapeRight];
    }
}

- (IBAction)previousVideo:(UIButton *)sender {
    if (_index == 0) {
        // [self alertMessage:@"已经是第一个视频了"];
        return;
    }
    _index--;
    [self setPlayerUrl];
    _nextButton.enabled = YES;
    self.tapActionAfterDur = 0;
    if (_index == 0) {
        _previousButton.enabled = NO;
    }
}

- (IBAction)nextVideoBtnClick:(UIButton *)sender {
    if (_index == _videoFiles.count - 1) {
        //[self alertMessage:@"已经是最后一个视频了"];
        return;
    }
    _index++;
    [self setPlayerUrl];
    _previousButton.enabled = YES;
    self.tapActionAfterDur = 0;
    if (_index == _videoFiles.count - 1) {
        _nextButton.enabled = NO;
    }
}

//检测屏幕旋转
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    // 计算方向
    if (size.width > size.height){
        self.currentOrientation = UIInterfaceOrientationLandscapeRight;
    }else {
        self.currentOrientation = UIInterfaceOrientationPortrait;
    }
    [self changeViewOrientation:size aniTime:coordinator.transitionDuration];
}

- (void)changeViewOrientation:(CGSize)size aniTime:(NSTimeInterval)aniTime {
    
    self.playViewHeightCon.constant = self.currentOrientation == UIInterfaceOrientationPortrait ? (size.width / size.height) * size.width:size.height;
    CGRect playerFrame;
    if (self.currentOrientation == UIInterfaceOrientationPortrait){
        self.playViewHeightCon.constant = size.width * kVideoAspectScale;
        self.leftSuperWidthCon.constant = kLeftViewPortraitWidth;
        self.topToolViewHeightCon.constant = 64;
        [self.plaYbutton setImage:[UIImage imageNamed:@"坚版播放"] forState:UIControlStateNormal];
        playerFrame = CGRectMake(0, 0, size.width, size.width * kVideoAspectScale);
        [self showOrHiddenToolView:NO];
        _bottomViewBottom.constant = kDevice_Is_iPhoneX?35:0;
        _leftPreViewConstraint.constant = 0;
    }else {
        self.playViewHeightCon.constant = size.height;
        self.leftSuperWidthCon.constant = kLeftViewLandscapeRightWidth;
        self.topToolViewHeightCon.constant = 49;
        [self.plaYbutton setImage:[UIImage imageNamed:@"横版播放"] forState:UIControlStateNormal];
        playerFrame = CGRectMake(0, 0, size.width, size.height);
        _bottomViewBottom.constant = 0;
        _leftPreViewConstraint.constant = kDevice_Is_iPhoneX?68:0;
    }
    
    [UIView animateWithDuration:aniTime animations:^{
        [self.playview setNeedsLayout];
        [self.leftSuperview setNeedsLayout];
        [self.topToolView setNeedsLayout];
        self.playerLayer.frame = playerFrame;
    } completion:^(BOOL finished) {
        [self.leftAnimationView configFrame:CGRectMake(0, 0, self.leftSuperWidthCon.constant, self.playViewHeightCon.constant)];
    }];
}

//想要的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;
}
-(BOOL)shouldAutorotate {
    return YES;
}
//由模态推出的视图控制器 优先支持的屏幕方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
}

- (void)timeStack {
    if (self.playerItem.duration.timescale != 0){
        // 计算播放当前进度
        Float64 currnetTime = CMTimeGetSeconds(self.playerItem.currentTime);
        
        Float64 totalSecond = CMTimeGetSeconds(self.playerItem.duration);
        CGFloat progress = currnetTime / totalSecond;
        
        self.videoSlider.value = progress;
        
        // 当前进度
        NSInteger proMin = (currnetTime / 60);
        NSInteger proSec =  (NSInteger)currnetTime % 60;
        
        // 总时长
        NSInteger totalMin = (totalSecond / 60);
        NSInteger totalSec =  (NSInteger)totalSecond % 60;
        
        self.currnetTimeLabel.text = [NSString stringWithFormat:@"%02zd:%02zd",proMin,proSec];
        self.totalTimeLabel.text = [NSString stringWithFormat:@"%02zd:%02zd",totalMin,totalSec];
        
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"swingSecond = %d",
                             (int)currnetTime];
        RLMResults *videoTrackItems = [self.currentVideo.videoTrackItems objectsWithPredicate:pred];
        
        if ([videoTrackItems count] > 0) {
            VideoTrackItem *trackItem = [videoTrackItems lastObject];
            [self updateLeftAirView:trackItem];
        }
    }
    if (self.currentOrientation == UIInterfaceOrientationLandscapeRight && self.bottomToolView.hidden == NO){
        self.tapActionAfterDur++;
    }
}

- (NSTimer *)timer {
    if (_timer == nil){
        _timer = [NSTimer scheduledTimerWithTimeInterval:kTimeerInterval target:self selector:@selector(timeStack) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (void)dealloc {
    YFLog(@"释放视频拍摄中的播放器");
}

// 已缓冲进度
- (NSTimeInterval)availableDurationRanges {
    NSArray *loadedTimeRanges = [_playerItem loadedTimeRanges]; // 获取item的缓冲数组
    
    // CMTimeRange 结构体 start duration 表示起始位置 和 持续时间
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue]; // 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds; // 计算总缓冲时间 = start + duration
    return result;
}

@end

@implementation VideoSliderView

- (CGRect)trackRectForBounds:(CGRect)bounds {
    return CGRectMake(0, 0, self.bounds.size.width, 6);
}

@end
